# -*- coding: utf-8 -*-

'''eof
name:申请企业注册年限过短
code:Ent_OperationPeriod_Short
tableName:
columnName:
groups:准入>企业业务信息校验
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''
'''由于应该取工商信息的时间，取烟草证的时间是有错的'''
'''
StartDate	String	是	工商信息有效期限_起始。取值示例:"2015-03-05"

1.按照实际日历，精确计算申请日期与成立日期相差Y年M月D日；
2.Factor = Y + M/12 + D/365 ，保留4位小数
'''
import sys
import pandas as pd
import datetime
import time
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding('utf-8')
def Ent_OperationPeriod_Short():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/']
    try:
        jbxx = EG['srcData'][0]['EG']['results'][0]['jbxx']
        if jbxx.has_key('esdate') and jbxx['esdate'] not in null_type_list:
            if Formate(jbxx['esdate']) is not None:
                date=Formate(jbxx['esdate'])
                start_date = datetime.datetime.strptime(date,'%Y-%m-%d')
                r = relativedelta(datetime.datetime.now(),start_date)
                date_range = r.years + r.months/float(12) + r.days/float(365)
                return round(date_range ,4)
            else:
                return 0
        else:
            return u'缺失值'
    except:
        return u'缺失值'

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date

result = Ent_OperationPeriod_Short()